package search

import (
	"context"
	protos "goim-pro/api/protos/salty"
	"goim-pro/internal/app/services/converters"
	"goim-pro/internal/app/services/search"
	errmsg "goim-pro/pkg/errors"
	"goim-pro/pkg/logs"
	"goim-pro/pkg/utils"
	"strings"
)

var (
	logger = logs.GetLogger("INFO")

	searchService search.ISearchService
)

type searchServer struct {
}

func New() protos.SearchServiceServer {
	searchService = search.New()
	return &searchServer{}
}

func (s *searchServer) Search(ctx context.Context, req *protos.GrpcReq) (resp *protos.GrpcResp, gRPCErr error) {
	resp, _ = utils.NewGRPCResp(protos.StatusCode_STATUS_OK, nil, "")

	var err error
	var searchReq protos.SearchReq
	if err = utils.UnmarshalGRPCReq(req, &searchReq); err != nil {
		resp.Code = protos.StatusCode_STATUS_BAD_REQUEST
		resp.Message = err.Error()
		logger.Errorf(`unmarshal error: %v`, err)
		return
	}

	userId := req.GetUserId()

	searchContent := strings.Trim(searchReq.SearchContent, "")
	if searchContent == "" {
		resp.Code = protos.StatusCode_STATUS_BAD_REQUEST
		resp.Message = errmsg.ErrInvalidParameters.Error()
		return
	}

	users, contacts, groups, tErr := searchService.Search(userId, searchReq.SearchType, searchContent)
	if tErr != nil {
		resp.Code = tErr.Code
		resp.Message = tErr.Detail
		return
	}

	reqContactResp := &protos.SearchResp{
		SearchResults: converters.ConvertSearchResult2Proto(users, contacts, groups),
	}
	anyData, err := utils.MarshalMessageToAny(reqContactResp)
	if err != nil {
		logger.Errorf("[search] response marshal message error: %s", err.Error())
		return
	}
	resp.Data = anyData
	return
}
